package com.du.web.sample.util;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class FileContentGenerator {

    private static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final int STRING_LENGTH = 50;
    private static final int ENTRY_COUNT = 50_000;
    private static final Random RANDOM = new Random();

    public static void main(String[] args) {
        // 示例：生成所有三种格式的文件
        generateFile(1, "D:\\output.json");
        generateFile(2, "D:\\output.properties");
        generateFile(3, "D:\\output.csv");
    }

    public static void generateFile(int type, String filename) {
        long startTime = System.currentTimeMillis();

        try {
            // 确定文件路径
            Path filePath = Paths.get(filename);

            // 生成内容并写入文件
            String content = generateContent(type);
            try (BufferedWriter writer = Files.newBufferedWriter(filePath, StandardCharsets.UTF_8)) {
                writer.write(content);
            }

            long endTime = System.currentTimeMillis();
            System.out.printf("Successfully generated %s in %d ms (Size: %.2f MB)%n",
                    filename, (endTime - startTime), Files.size(filePath) / (1024.0 * 1024.0));
        } catch (IOException e) {
            System.err.println("Error writing file: " + e.getMessage());
        }
    }

    public static String generateContent(int type) {
        // 生成2万条键值对
        List<Map.Entry<String, String>> entries = generateEntries();

        switch (type) {
            case 1: // JSON
                return generateJsonContent(entries);
            case 2: // Properties
                return generatePropertiesContent(entries);
            case 3: // CSV
                return generateCsvContent(entries);
            default:
                throw new IllegalArgumentException("Invalid type: " + type);
        }
    }

    // 生成2万条键值对
    private static List<Map.Entry<String, String>> generateEntries() {
        return IntStream.range(0, ENTRY_COUNT)
                .parallel()
                .mapToObj(i -> new AbstractMap.SimpleEntry<>(
                        generateRandomKey(),
                        generateRandomValue()))
                .collect(Collectors.toList());
    }

    // 生成随机键（带点号分隔符）
    private static String generateRandomKey() {
        StringBuilder sb = new StringBuilder(STRING_LENGTH);
        for (int i = 0; i < STRING_LENGTH; i++) {
            sb.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length())));
        }

        // 随机插入点号（1-5个）以创建嵌套结构
        int dotCount = RANDOM.nextInt(5) + 1;
        for (int i = 0; i < dotCount; i++) {
            int pos = RANDOM.nextInt(sb.length() - 1) + 1;
            sb.insert(pos, '.');
        }

        return sb.toString();
    }

    // 生成随机值（纯随机字符串）
    private static String generateRandomValue() {
        StringBuilder sb = new StringBuilder(STRING_LENGTH);
        for (int i = 0; i < STRING_LENGTH; i++) {
            sb.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length())));
        }
        return sb.toString();
    }

    // 生成JSON内容（数组格式）
    private static String generateJsonContent(List<Map.Entry<String, String>> entries) {
        StringBuilder sb = new StringBuilder(ENTRY_COUNT * 120);
        sb.append("[\n");

        Iterator<Map.Entry<String, String>> iterator = entries.iterator();
        for (int i = 0; i < entries.size(); i++) {
            Map.Entry<String, String> entry = iterator.next();
            String key = entry.getKey();
            String value = entry.getValue();

            // 构建嵌套结构
            Map<String, Object> resultMap = buildNestedMap(key, value);

            // 转换为JSON字符串
            sb.append(mapToJsonString(resultMap, 1));

            if (i < entries.size() - 1) {
                sb.append(",\n");
            }
        }

        sb.append("\n]");
        return sb.toString();
    }

    // 构建嵌套Map结构
    private static Map<String, Object> buildNestedMap(String key, String value) {
        Map<String, Object> resultMap = new LinkedHashMap<>();
        Map<String, Object> currentMap = resultMap;

        String[] keyParts = key.split("\\.");
        for (int i = 0; i < keyParts.length - 1; i++) {
            Map<String, Object> newMap = new LinkedHashMap<>();
            currentMap.put(keyParts[i], newMap);
            currentMap = newMap;
        }

        currentMap.put(keyParts[keyParts.length - 1], value);
        return resultMap;
    }

    // 递归将Map转换为JSON字符串
    private static String mapToJsonString(Map<String, Object> map, int indentLevel) {
        StringBuilder sb = new StringBuilder();
        String indent = "";

        sb.append(indent).append("{\n");

        int count = 0;
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (count++ > 0) sb.append(",\n");
            sb.append(indent).append("\"").append(entry.getKey()).append("\": ");

            if (entry.getValue() instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<String, Object> nestedMap = (Map<String, Object>) entry.getValue();
                sb.append(mapToJsonString(nestedMap, indentLevel + 1));
            } else {
                sb.append("\"").append(entry.getValue()).append("\"");
            }
        }

        sb.append("\n").append(indent).append("}");
        return sb.toString();
    }

    // 生成Properties内容
    private static String generatePropertiesContent(List<Map.Entry<String, String>> entries) {
        StringBuilder sb = new StringBuilder(ENTRY_COUNT * 120);

        for (Map.Entry<String, String> entry : entries) {
            sb.append(entry.getKey())
                    .append('=')
                    .append(entry.getValue())
                    .append('\n');
        }

        return sb.toString();
    }

    // 生成CSV内容
    private static String generateCsvContent(List<Map.Entry<String, String>> entries) {
        StringBuilder sb = new StringBuilder(ENTRY_COUNT * 120);
        sb.append("dicKey,dicValue\n"); // 添加标题行

        for (Map.Entry<String, String> entry : entries) {
            sb.append(escapeCsv(entry.getKey()))
                    .append(',')
                    .append(escapeCsv(entry.getValue()))
                    .append('\n');
        }

        return sb.toString();
    }

    // CSV格式转义
    private static String escapeCsv(String input) {
        if (input.contains("\"") || input.contains(",") || input.contains("\n")) {
            return "\"" + input.replace("\"", "\"\"") + "\"";
        }
        return input;
    }
}
